local chouguo = fk.CreateSkill {
  name = "lingling__chouguo",
}

Fk:loadTranslationTable{
  ["lingling__chouguo"] = "愁国",
  [":lingling__chouguo"] = "出牌阶段限一次，你可以令所有角色依次重铸一张牌，然后你可以分配任意张点数之和不大于7的被重铸牌。",

  ["#lingling__chouguo"] = "愁国：令所有角色依次重铸一张牌，然后分配点数之和不大于7的被重铸牌",
  ["#lingling__chouguo-recast"] = "愁国：请重铸一张牌",
  ["#lingling__chouguo-give"] = "愁国：你可以将点数之和不大于7的牌任意分配（已选%arg点）",
}

chouguo:addEffect("active", {
  anim_type = "control",
  prompt = "#lingling__chouguo",
  card_num = 0,
  target_num = 0,
  can_use = function(self, player)
    return player:usedSkillTimes(chouguo.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = effect.from
    local targets = room:getAlivePlayers()
    room:doIndicate(player, targets)
    local cards = {}
    for _, p in ipairs(targets) do
      if not p:isNude() and not p.dead then
        local card = room:askToCards(p, {
          min_num = 1,
          max_num = 1,
          include_equip = true,
          skill_name = chouguo.name,
          cancelable = false,
          prompt = "#lingling__chouguo-recast",
        })
        table.insertIfNeed(cards, card[1])
        room:recastCard(card, p, chouguo.name)
      end
    end
    cards = table.filter(cards, function (id)
      return table.contains(room.discard_pile, id) and Fk:getCardById(id).number <= 7
    end)
    if player.dead or #cards == 0 then return end
    local list, total = {}, 0
    local all_cards = table.simpleClone(cards)
    while total < 7 do
      cards = table.filter(cards, function (id)
        return Fk:getCardById(id).number <= 7 - total
      end)
      if #cards == 0 then break end
      local success, dat = room:askToUseActiveSkill(player, {
        skill_name = "lingling__chouguo_active",
        prompt = "#lingling__chouguo-give:::"..total,
        extra_data = {
          total = total,
          all_cards = all_cards,
          cards = cards,
        },
      })
      if success and dat then
        local to = dat.targets[1]
        list[to.id] = list[to.id] or {}
        table.insertTable(list[to.id], dat.cards)
        for _, id in ipairs(dat.cards) do
          local card = Fk:getCardById(id)
          room:setCardMark(card, "@DistributionTo", Fk:translate(to.general))
          total = total + card.number
          table.removeOne(cards, id)
        end
      else
        break
      end
    end
    for _, id in ipairs(all_cards) do
      room:setCardMark(Fk:getCardById(id), "@DistributionTo", 0)
    end
    room:doYiji(list, player, chouguo.name)
  end,
})

return chouguo
